<template>
  <div>
    <a-page-header style="border: 1px solid rgb(235, 237, 240)" title="添加文章" @back="() => this.$router.go(-1)" />
    <!-- 表单区域 -->
    <a-card style="width: 800px; margin: 40px auto">
      <a-spin :spinning="confirmLoading">
        <a-form :form="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 12 }">
          <a-form-item label="所属分类">
            <a-select v-decorator="['categoryId', validatorRules.categoryId]" @change="selecBuildingChange">
              <a-select-option
                :value="item.id"
                v-for="(item, index) in categoryUl"
                :key="index"
              >
                {{ item.name }}
              </a-select-option>
              <a-icon slot="prefix" type="user" />
            </a-select>
          </a-form-item>
          <a-form-item label="标题">
            <a-input v-decorator="['title', validatorRules.title]" placeholder="请输入标题" />
          </a-form-item>
          <a-form-item label="缩略图">
            <image-upload v-model="images" text="上传" :isMultiple="false"></image-upload>
            <a-tag color="orange">上图：选择多图-每张图-尺寸（900*600）大小（小于100k）</a-tag>
          </a-form-item>
          <a-form-item label="缩略图显示状态">
            <a-radio-group v-model="imagesMode" :default-value="0" name="imagesMode">
              <a-radio :value="0">拉伸填充</a-radio>
              <a-radio :value="1">原比例缩放</a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item label="摘要">
            <a-textarea cols="30" rows="5" v-model="summary" :maxLength="200" placeholder="请输入摘要"></a-textarea>
            <a-tag color="#cdcdcd">{{summary.length}}/200</a-tag>
          </a-form-item>
          <a-form-item label="下载信息显示">
            <a-radio-group v-model="showDownInfo" :default-value="1" name="showDownInfo">
              <a-radio :value="0">不显示</a-radio>
              <a-radio :value="1">显示</a-radio>
            </a-radio-group>
          </a-form-item>
          <div class="is_showDownInfo" v-show="showDownInfo == 1">
            <a-form-item label="下载方式">
              <a-textarea cols="30" rows="5" v-decorator="['downAddress', showDownInfo == 1?validatorRules.downAddress:{}]" placeholder="请输入下载方式（地址）" ></a-textarea>
            </a-form-item>
            <a-form-item label="文件大小">
              <a-input v-decorator="['fileSize', {}]" placeholder="请输入文件大小" />
            </a-form-item>
            <a-form-item label="文件版本">
              <a-input v-decorator="['fileVersion', {}]" placeholder="请输入文件版本" />
            </a-form-item>
            <a-form-item label="下载次数">
              <a-input-number style="width: 100%" :min="0" v-decorator="['downTimes', {}]" placeholder="请输入下载次数" />
            </a-form-item>
          </div>
          <a-form-item label="支持语言">
            <a-input v-decorator="['supportLanguage', validatorRules.supportLanguage]" placeholder="请输入支持语言" />
          </a-form-item>
          <a-form-item label="标签">
            <a-row>
              <a-col :span="18">
                <a-select mode="multiple" placeholder="请点击右侧进行搜索查询" v-model="tagNames" :options="selectOptions" disabled :open="selectOpen" style="width: 100%;" @dropdownVisibleChange="handleDropdownVisibleChange" @click.native="visible=(buttons?visible:true)" />
              </a-col>
              <a-col :span="6">
                <a-button type="primary" style="margin-left: 5px" @click="onSearchTag"> 添加标签 </a-button>
              </a-col>
            </a-row>
          </a-form-item>
          <!-- <a-form-item label="热门推荐">
            <a-input-number style="width: 100%" :min="0" v-decorator="['hot', validatorRules.hot]" placeholder="数字从小到大排序" />
          </a-form-item>
          <a-form-item label="置顶推荐">
            <a-input-number style="width: 100%" :min="0" v-decorator="['top', validatorRules.top]" placeholder="数字从小到大排序" />
          </a-form-item>
          <a-form-item label="推荐指数">
            <a-input-number style="width: 100%" :min="0" v-decorator="['side', validatorRules.side]" placeholder="数字从小到大排序" />
          </a-form-item> -->
          <a-form-item label="状态">
            <a-radio-group v-decorator="['status', validatorRules.status]" name="status">
              <a-radio :value="0">下架</a-radio>
              <a-radio :value="1">上架</a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item label="浏览次数">
            <a-input-number style="width: 100%" :min="0" v-decorator="['browse',{initialValue: 0}]" placeholder="请输入浏览次数" />
          </a-form-item>
          <a-form-item label="作者">
            <a-input v-decorator="['author', {}]" placeholder="请输入作者" />
          </a-form-item>
          <a-form-item label="视频">  
            <video-upload v-model="video" text="上传" @videoVal="videoVal"></video-upload>
          </a-form-item>
        </a-form>
        <mavon-editor ref="md" :style="'height:' + height+';margin-bottom: 30px;'" @imgAdd="imgAdd" v-model="mdEditor" :toolbars="toolbars" />
        <div class="but_box">
          <a-button @click="submit" type="primary">提交</a-button>
        </div>
      </a-spin>
    </a-card>
    <!-- 弹框区域 -->
    <blogQueryModal ref="modalForm" @choose="choose"></blogQueryModal>
  </div>
</template>
<script>
import blogQueryModal from '@/views/blog/modules/blogQueryModal';
import ImageUpload from '@/components/ImageUpload';
import VideoUpload from '@/components/VideoUpload';
import MarkDown from '@/views/components/MarkDown';
import { getAdd, getDetail, getUpdate } from '@/api/blog/blogList';
import { getList } from '@/api/blog/blogClass';
import { upload } from '@/utils/upload';
import { mapGetters } from 'vuex';
export default {
  name: 'RoomAdd',
  components: { ImageUpload, blogQueryModal, MarkDown, VideoUpload },
  data() {
    return {
      confirmLoading: false,
      id: null,
      categoryUl: [],
      validatorRules: {
        categoryId: { rules: [{ required: true, message: '请输入所属分类!' }] },
        title: { rules: [{ required: true, message: '请输入标题!' }] },
        summary: { rules: [{ required: true, message: '请输入摘要!' },{ min: 1, max: 80, message: '请不要超过80个字', trigger: 'blur' },] },
        supportLanguage: {
          rules: [{ required: true, message: '请输入支持语言!' }],
          initialValue: '中文'
        },
        status: { rules: [{ required: true, message: '请输入状态!' }], initialValue: 1 },
        downAddress:{ rules: [{ required: true, message: '请输入下载地址!' }]},
      },
      showDownInfo:1,
      images: [],
      imagesMode:0,
      height: document.documentElement.clientHeight - 200 + 'px',
      summary:'', //摘要
      tagNames: [], // tag 标签
      tagIds: [], // tag 标签
      video:'', //视频
      selectOptions: [],
      visible: false,
      selectOpen: false,
      mdEditor: '',
      form: this.$form.createForm(this, { name: 'coordinated' }),
      toolbars: {
        bold: true, // 粗体
        italic: true, // 斜体
        header: true, // 标题
        underline: true, // 下划线
        strikethrough: true, // 中划线
        mark: false, // 标记
        superscript: true, // 上角标
        subscript: true, // 下角标
        quote: true, // 引用
        ol: true, // 有序列表
        ul: true, // 无序列表
        link: true, // 链接
        imagelink: true, // 图片链接
        code: true, // code
        table: true, // 表格
        fullscreen: true, // 全屏编辑
        readmodel: true, // 沉浸式阅读
        htmlcode: true, // 展示html源码
        help: true, // 帮助
        /* 1.3.5 */
        undo: true, // 上一步
        redo: true, // 下一步
        trash: true, // 清空
        save: false, // 保存（触发events中的save事件）
        /* 1.4.2 */
        navigation: true, // 导航目录
        /* 2.1.8 */
        alignleft: true, // 左对齐
        aligncenter: true, // 居中
        alignright: true, // 右对齐
        /* 2.2.1 */
        subfield: true, // 单双栏模式
        preview: true, // 预览
      },
    };
  },
  created() {
    const token = this.$store.getters.token;
    this.headers = { 'X-Access-Token': token };
    this.categoryList();
    if (this.$route.query.id) {
      // 编辑
      this.edit(this.$route.query.id);
    } else {
      //添加
    }
  },
  mounted() {
    const that = this;
    window.onresize = function temp() {
      that.height = document.documentElement.clientHeight - 200 + 'px';
    };
  },
  computed: {
    ...mapGetters(['imagesUploadApi']),
  },
  methods: {
    videoVal(val){
      this.video = val
    },
    // 编辑
    edit(id) {
      this.confirmLoading = true;
      this.id = id;
      getDetail(id)
        .then((res) => {
          let data = res.result;
          this.$nextTick(() => {
            this.form.setFieldsValue({
              categoryId: data.categoryId,
              title: data.title,
              fileSize: data.fileSize,
              fileVersion: data.fileVersion,
              downAddress:data.downAddress,
              downTimes: data.downTimes,
              supportLanguage: data.supportLanguage,
              browse: data.browse,
              status: data.status,
              author: data.author,
            });
            this.summary = data.summary
            this.showDownInfo = data.showDownInfo
            this.images = data.img ? data.img : '';
            this.imagesMode = data.mode?data.mode:0;
            this.tagIds = data.tagIds;
            this.video = data.video?data.video:'';
            this.mdEditor = data.content ? data.content : '';
            this.tagNames = data.tags.map((obj) => {
              obj = obj.name;
              return obj;
            });
          });
        })
        .finally(() => {
          this.confirmLoading = false;
        });
    },
    // 分类列表
    categoryList() {
      getList().then((res) => {
        this.categoryUl = res.result;
      });
    },
    // 查询标签
    onSearchTag() {
      this.$refs.modalForm.search(this.tagIds);
      this.$refs.modalForm.title = '查询标签（最多选择五个）';
    },
    // 选择标签赋值
    choose(record) {
      let that = this
      this.$nextTick(() => {
        that.tagNames = record.map((obj) => {
          obj = obj.name;
          return obj;
        });
        that.tagIds = record.map((obj) => {
          obj = obj.id;
          return obj;
        });
      });
    },
    // 选择分类
    selecBuildingChange(data) {
      this.form.setFieldsValue({
        categoryId: data,
      });
    },
    //md编辑器添加图片
    imgAdd(pos, $file) {
      upload(this.imagesUploadApi, $file).then((res) => {
        const data = res.data.result;
        const url = data;
        this.$refs.md.$img2Url(pos, url);
      });
    },
    // 确定
    submit() {
      this.form.validateFields((err, values) => {
        if (!err) {
          // 编辑
          values = {
            ...values,
            img: this.images.length == 0 ? '' : this.images.split(',')[0],
            mode:this.imagesMode,
            content: this.mdEditor,
            tagIds: this.tagIds,
            status: values.status,
            showDownInfo: this.showDownInfo,
            video:this.video,
            browse:values.browse ? values.browse : 0,
            summary:this.summary,
          };
          if (this.$route.query.id) {
            // 编辑
            values = {
              ...values,
              id: this.id,
            };
            getUpdate(values).then(
              (res) => {
                this.$message.success('提交成功');
                this.form.resetFields();
                this.$router.replace({ path: '/blogList' });
              },
              (err) => {
                this.$message.warning('提交失败');
              }
            );
          } else {
            // 新增
            getAdd(values).then(
              (res) => {
                this.$message.success('提交成功');
                this.form.resetFields();
                this.$router.replace({ path: '/blogList' });
              },
              (err) => {
                this.$message.warning('提交失败');
              }
            );
          }
        }
      });
    },
    handleDropdownVisibleChange() {
      // 解决antdv自己的bug —— open 设置为 false 了，点击后还是添加了 open 样式，导致点击事件失效
      this.selectOpen = true;
      this.$nextTick(() => {
        this.selectOpen = false;
      });
    },
    // 重置
    reset() {
      this.form.resetFields();
    },
  },
};
</script>
<style scoped>
.is_showDownInfo {
  background: #f1f1f1;
  padding: 20px;
  margin-bottom: 20px;
}
.but_box{
  text-align: center;
}
</style>